package com.bytech.comment.biz.controller.comment;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytech.comment.biz.service.comment.CommentService;
import com.bytech.comment.biz.service.commentThumb.CommentThumbService;
import com.bytech.common.annotation.UserAgent;
import com.bytech.common.biz.controller.base.BasicController;
import com.bytech.common.biz.entity.article.Article;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.blogUser.BlogUser;
import com.bytech.common.biz.entity.blogUser.BlogUserAgent;
import com.bytech.common.biz.entity.comment.Comment;
import com.bytech.common.biz.entity.comment.CommentDto;
import com.bytech.common.biz.entity.comment.CommentQuery;
import com.bytech.common.biz.entity.commentThumb.CommentThumb;
import com.bytech.common.biz.enums.comment.CommentTypeEnum;
import com.bytech.common.config.AppGlobalConstants;
import com.bytech.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author Zhao
 * @Create 2021/8/10 18:50
 */
@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController extends BasicController {

    @Resource
    private CommentService commentService;
    @Resource
    private CommentThumbService commentThumbService;

    @GetMapping("/pageByQuery")
    public BaseResult<Page<CommentDto>> pageArticleComments(CommentQuery<Comment> commentQuery, @UserAgent BlogUserAgent userAgent) {
        commentQuery.setMyUserId(userAgent.getId());
        commentQuery.setSize(5L);
        return BaseResult.<Page<CommentDto>>success().data(commentService.pageCommentByQuery(commentQuery)).build();
    }

    @GetMapping("/statMessage")
    public BaseResult<Integer> statMessageInfo(){
        return BaseResult.<Integer>success().data(commentService.countByType(CommentTypeEnum.MESSAGE.getValue())).build();
    }

    /**
     * 获取最新的 N 条评论/留言
     */
    @GetMapping("/latest")
    public BaseResult<List<CommentDto>> getLatestComments(String commentType, Integer limit, @UserAgent BlogUserAgent userAgent) {
        limit = limit == null ? 5 : limit;
        return BaseResult.<List<CommentDto>>success().data(commentService.getLatestComments(commentType, limit, userAgent.getId())).build();
    }

    @GetMapping("/countByType")
    public BaseResult<Integer> countByType(@RequestParam("type") String type) {
        if (CommentTypeEnum.of(type).equals(CommentTypeEnum.UNKNOWN)) {
            return BaseResult.<Integer>error("评论/留言类型不存在！").data(null).build();
        }
        return BaseResult.<Integer>success().data(commentService.countByType(type)).build();
    }

    @GetMapping("/countByArticle")
    public BaseResult<Integer> countByArticle(@RequestParam("articleId") String articleId) {
        return BaseResult.<Integer>success().data(commentService.countByArticle(articleId)).build();
    }

    @PostMapping("/deleteByArticleId")
    public BaseResult<Integer> deleteByArticleId(@RequestParam("articleId") String articleId) {
        return commentService.deleteByArticleId(articleId);
    }

    @PostMapping("/submitComment")
    public BaseResult<CommentDto> doSubmitComment(CommentDto commentDto, @UserAgent BlogUserAgent userAgent, HttpServletRequest request, HttpServletResponse response) {
        BaseResult<BlogUserAgent> commentResult = commentService.doComment(commentDto, userAgent, request);
        if (commentResult.isFailure()) {
            return BaseResult.<CommentDto>error("评论失败：" + commentResult.getMsg()).build();
        }
        BlogUserAgent curUserAgent = commentResult.getData();
        // 总是更新 session
        HttpSession session = request.getSession();
        session.removeAttribute(AppGlobalConstants.BLOG_USER_SESSION_KEY);
        session.setAttribute(AppGlobalConstants.BLOG_USER_SESSION_KEY, curUserAgent);
        session.setMaxInactiveInterval(AppGlobalConstants.BLOG_USER_SESSION_EXPIRED);
        Cookie[] cookies = request.getCookies();
        if (!ArrayUtils.isEmpty(cookies)) {
            Optional<Cookie> opCookie = Arrays.stream(cookies).filter(e -> e.getName().equals(AppGlobalConstants.BLOG_USER_COOKIE_KEY)).findFirst();
            if (!opCookie.isPresent()) {
                // 记住评论用户
                Cookie cookie = new Cookie(AppGlobalConstants.BLOG_USER_COOKIE_KEY, curUserAgent.getToken());
                cookie.setMaxAge(AppGlobalConstants.BLOG_USER_COOKIE_EXPIRED);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return BaseResult.<CommentDto>success("提交成功").data(commentDto).build();
    }

    /**
     * 评论/留言点赞接口
     *
     * @return 返回一个整数 代表前端点赞数需变化的值 +1、-1、0不变
     */
    @PostMapping("/toggleComment")
    public BaseResult<Integer> doToggleComment(Long commentId, @UserAgent BlogUserAgent userAgent) {
        Comment comment = commentService.getById(commentId);
        if (comment == null) {
            return BaseResult.<Integer>error("您点赞的评论不存在").data(0).build();
        }
        if (StringUtils.isBlank(userAgent.getId())) {
            return BaseResult.<Integer>error("还未生您的用户信息哦，在您第一次评论/留言之后即会生成您的用户信息").data(0).build();
        }
        return commentThumbService.toggleThumb(commentId, userAgent.getId());
    }

    @GetMapping("/pageCommentReply")
    public BaseResult<List<CommentDto>> pageCommentReply(Long commentId, Integer pageNum, @UserAgent BlogUserAgent userAgent) {
        return commentService.pageCommentReply(commentId, pageNum, userAgent);
    }
}
